package com.taikang.system.controller.admin;

import java.io.File;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.json.simple.JSONObject;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.taikang.base.controller.BaseController;
import com.taikang.base.token.TokenValidate;
import com.taikang.system.dto.SysRegionCondition;
import com.taikang.system.entity.SysRegion;
import com.taikang.system.entity.SysRegionCircle;
import com.taikang.system.form.SysRegionCircleForm;
import com.taikang.system.service.ISysRegionCircleService;
import com.taikang.system.service.ISysRegionService;

/**
 * 商圈
 * @author taikang
 * @create-time 2015-10-8   下午12:19:53
 * @version 1.0
 */
@Controller("sysRegionCircleController")
@Scope("prototype")
@RequestMapping(value = "/admin/system/region/circle")
public class SysRegionCircleController extends BaseController {

	@Resource(name = "sysRegionCircleServiceImpl")
	private ISysRegionCircleService sysRegionCircleService;
	@Resource(name = "sysRegionServiceImpl")
	private ISysRegionService sysRegionService;


	/**
	 * 首页
	 * @return 
	 */
	@RequestMapping(value = "/index.htm", method = RequestMethod.GET)
	public String index(HttpServletRequest request){
		SysRegionCondition regionCondition = new SysRegionCondition();
		regionCondition.setLevel(2);
		List<SysRegion> regionList = sysRegionService.listSysRegionsByCondition(regionCondition);
		request.setAttribute("regionList",regionList);
		return "/admin/system/sys_region_circle_index";
	}
	
	/**
	 * 跳转到添加页面
	 * @return 
	 */
	@RequestMapping(value = "/add.htm", method = RequestMethod.GET)
	public ModelAndView add(@ModelAttribute SysRegionCircleForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		ModelAndView view = new ModelAndView();
		view.setViewName("/admin/system/sys_region_circle_add");
 		Map<String, Object> data = view.getModel();
 		SysRegionCondition condition = new SysRegionCondition();
 		condition.setParentId(0L);
 		data.put("regionList",sysRegionService.listSysregionByCondition(condition));
		return view;
	}
	/**
	 * 跳转到修改页面
	 * @return 
	 */
	@RequestMapping(value = "/update.htm", method = RequestMethod.GET)
	public ModelAndView update(@ModelAttribute SysRegionCircleForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		ModelAndView view = new ModelAndView();
		view.setViewName("/admin/system/sys_region_circle_add");
 		Map<String, Object> data = view.getModel();
 		SysRegionCondition condition = new SysRegionCondition();
 		condition.setParentId(0L);
 		data.put("regionList",sysRegionService.listSysregionByCondition(condition));
 		SysRegionCircle item = sysRegionCircleService.getSysRegionCircleById(model.getCircleId());
 		data.put("item",item);
		return view;
	}
	/**
	 * 保存商圈
	 * @return 
	 */
	@RequestMapping(value = "/doAdd.htm", method = RequestMethod.POST)
	public ModelAndView doAdd(@ModelAttribute SysRegionCircleForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		try {
			if(StringUtils.isBlank(model.getItem().getId())){
				sysRegionCircleService.add(model.getItem());
			}else{
			 	SysRegion sysRegion = sysRegionService.getSysRegionById(model.getItem().getRegionId());
			 	model.getItem().setRegionId(sysRegion.getId());
			 	model.getItem().setRegionName(sysRegion.getName());
				sysRegionCircleService.update(model.getItem());
			}
			return ajaxJSON(Status.success, "添加成功");
		} catch (Exception e) {
			String msg = "保存省市区基础表时发生异常：" + e.getMessage();
			logger.error(msg,e);
			return ajaxJSON(Status.error, "保存失败，请稍后重试");
		}
	}
	/**
	 * 为商圈设置城市
	 * @return 
	 */
	@RequestMapping(value = "/fitCity.htm", method = RequestMethod.POST)
	public ModelAndView fitCity(@ModelAttribute SysRegionCircleForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		try {
			sysRegionCircleService.fitCity(model.getCondition());
			return ajaxJSON(Status.success, "添加成功");
		} catch (Exception e) {
			String msg = "保存省市区基础表时发生异常：" + e.getMessage();
			logger.error(msg,e);
			return ajaxJSON(Status.error, "保存失败，请稍后重试");
		}
	}
	/**
	 * 为商圈设置城市
	 * @param model
	 * @param request
	 * @param response
	 * @param session
	 */
	@RequestMapping(value = "/selectCity.htm",method = RequestMethod.GET)
	public ModelAndView selectCity(@ModelAttribute SysRegionCircleForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		ModelAndView view = new ModelAndView();
		view.setViewName("/admin/system/sys_region_circle_detail");
		Map<String, Object> data = view.getModel();
		data.put("circleId", model.getCircleId());
		data.put("flag", model.getFlag());
		return view;
	}
	
	/**
	 * 分页查询
	 * @return 
	 */
	@RequestMapping(value = "/listSysRegionCircleByPage.htm", method = RequestMethod.POST)
	public void listSysRegionCircleByPage(@ModelAttribute SysRegionCircleForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		try{
			sysRegionCircleService.listSysRegionCircleByPage(model.getPageResult(),model.getCondition());
			JSONObject root = toPageJson(model.getPageResult(), new String[]{"id","name","createDate","regionId","regionName","sort"});
			ajaxPageResult(root,response);
		}catch(Exception ex){
			String msg = "查询商圈管理时发生异常："+ex.getMessage();
			logger.error(msg,ex);
		}	}

	/**
	 * 保存商圈管理
	 * @return 
	 */
	@RequestMapping(value = "/edit.htm", method = RequestMethod.GET)
	public ModelAndView edit(@ModelAttribute SysRegionCircleForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		ModelAndView view = new ModelAndView();
		view.setViewName("");
		Map<String,Object> data = view.getModel();
		if(StringUtils.isNotBlank(model.getItem().getId())){
			SysRegionCircle item = sysRegionCircleService.getSysRegionCircleById(model.getItem().getId());
			data.put("item", item);
		}
		return view;
	}

	/**
	 * 保存商圈管理
	 * @return 
	 */
	@RequestMapping(value = "/saveSysRegionCircle.htm", method = RequestMethod.POST)
	@TokenValidate
	public ModelAndView saveRole(@ModelAttribute SysRegionCircleForm model,HttpServletRequest request,HttpSession session){
		try {
			if(StringUtils.isBlank(model.getItem().getId())){
				sysRegionCircleService.add(model.getItem());
			}else{
				sysRegionCircleService.update(model.getItem());
			}
			return ajaxJSON(Status.success,"保存成功");
		} catch (Exception e) {
			String msg = "保存商圈管理时发生异常：" + e.getMessage();
			logger.error(msg,e);
			return ajaxJSON(Status.error, "保存失败，请稍后重试");
		}
	}
	/**
	 * 删除SysRegionCircle
	 * @return 
	 */
	@RequestMapping(value = "/del.htm", method = RequestMethod.POST)
	public ModelAndView del(@ModelAttribute SysRegionCircleForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		try {
			sysRegionCircleService.delByIds(model.getSelIds().split(","));
			return ajaxJSON(Status.success,"删除成功");
		} catch (Exception e) {
			String msg = "删除商圈管理时发生异常：" + e.getMessage();
			logger.error(msg,e);
			return ajaxJSON(Status.error, "删除失败，请稍后重试");
		}
	}
	/**
	 * 导入商圈
	 * @return
	 */
	@RequestMapping(value = "/doImport.htm", method = RequestMethod.POST)
	public ModelAndView doImport(@ModelAttribute SysRegionCircleForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		String errorMessage = "";
		try {
			String path = model.getFilePath();
			path=getRealPath(path, request);
			errorMessage = sysRegionCircleService.importXls(path);	
			if(StringUtils.isBlank(errorMessage)){
				errorMessage = "导入成功";
			}
			// 导入完毕删除文件
			File file = new File(path);
			file.delete();
		} catch (Exception e) {
			return ajaxJSON(Status.error, e.getMessage());
		}finally{
		}
		
		return ajaxJSON(Status.success , errorMessage);
	}


}

